package com.oncliedisk.administrator.Base;

import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.oncliedisk.administrator.DB.Dao;
import com.oncliedisk.administrator.interfaces.OnDownLoadFinishListener;
import com.oncliedisk.administrator.adapter.FileAdapter;
import com.oncliedisk.administrator.content.FileConfig;
import com.oncliedisk.administrator.content.OnlineConfig;
import com.oncliedisk.administrator.interfaces.OnFileDownListener;
import com.oncliedisk.administrator.model.EntryModel;
import com.oncliedisk.administrator.model.FileTaskModel;
import com.oncliedisk.administrator.onlinedisk.R;
import com.oncliedisk.administrator.utils.FileUtils;
import com.oncliedisk.administrator.utils.HttpUtils;
import com.vdisk.android.VDiskAuthSession;
import com.vdisk.net.VDiskAPI;
import com.vdisk.net.exception.VDiskException;
import com.vdisk.net.session.AppKeyPair;
import com.vdisk.net.session.Session;
import com.ypy.eventbus.EventBus;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2015/12/10.
 */
public class BaseActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener {
    protected boolean isMulChoice = false; //是否多选
    protected List<EntryModel> selectid = new ArrayList<>();
    protected LinearLayout showLongLayout; //下面的工具栏
    protected FileAdapter adapter; //适配器
    protected ListView listView; // ListView
    private TextView mTitle; //标题
    private ImageView mBack; //返回
    private RelativeLayout layout_title; //标题布局
    private RelativeLayout layout_num; //选中个数布局
    private TextView selecedNumber; //选中的个数
    private int selecedIndex; //选中个数
    private int currSelseNum; //当前选中了几个
    private ImageView openFile_img; //打开文件图标
    private TextView openFile_txt; //打开文件文字
    private int[] img_grey = {R.drawable.open_grey, R.drawable.down_grey, R.drawable.delete_grey, R.drawable.more_grey};
    private int[] img_white = {R.drawable.open_white, R.drawable.down_white, R.drawable.delete_white, R.drawable.more_white};
    private boolean isAllSeleced = false; //全选状态
    private PopupWindow window;
    private AlertDialog alertDialog; //重命名
    private EditText newFileNmae;
    private String currId = FileConfig.IS_ROOT; //当前ID
    protected String currPosition = "0";
    private String paths = "网盘"; //路径
    VDiskAPI<VDiskAuthSession> mApi;
    private VDiskAuthSession session;
    protected String currPath = "/"; //当前ID
    protected boolean isSearch; //是搜索页面
    private int downNumb; //总下载数
    private int currDownNum; //当前下载了多少
    protected TextView search_result;
    private LinearLayout search_layouts;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_base);
        initWeight();
        initVid();
        initListener();
    }

    public void initAdapter(List<EntryModel> data) {
        adapter = new FileAdapter(data, getActivity(),listView);
    }

    private void initListener() {
        findViewById(R.id.base_open).setOnClickListener(this);
        findViewById(R.id.base_delete).setOnClickListener(this);
        findViewById(R.id.base_down).setOnClickListener(this);
        findViewById(R.id.base_more).setOnClickListener(this);
        mBack.setOnClickListener(this);
        listView.setOnItemClickListener(this);
        listView.setOnItemLongClickListener(this);
        for (int i = 0; i < layout_num.getChildCount(); i++) {
            layout_num.getChildAt(i).setOnClickListener(this);
        }
    }

    private void initWeight() {
        showLongLayout = (LinearLayout) findViewById(R.id.base_layout);
        listView = (ListView) findViewById(R.id.base_listview);
        mTitle = (TextView) findViewById(R.id.base_title);
        mBack = (ImageView) findViewById(R.id.base_back);
        layout_title = (RelativeLayout) findViewById(R.id.base_layout_title);
        layout_num = (RelativeLayout) findViewById(R.id.base_layout_num);
        selecedNumber = (TextView) findViewById(R.id.base_selenum);
        LinearLayout open_layout = (LinearLayout) showLongLayout.getChildAt(0);
        openFile_img = (ImageView) open_layout.getChildAt(0);
        openFile_txt = (TextView) open_layout.getChildAt(1);
        search_result = (TextView) findViewById(R.id.search_result);
        search_layouts = (LinearLayout) findViewById(R.id.search_layout);
    }

    private void initVid() {
        AppKeyPair appKeyPair = new AppKeyPair(OnlineConfig.CONSUMER_KEY,
                OnlineConfig.CONSUMER_SECRET);

        session = VDiskAuthSession.getInstance(getActivity(), appKeyPair,
                Session.AccessType.APP_FOLDER);

        mApi = new VDiskAPI<VDiskAuthSession>(session);
    }

    /**
     * 设置标题
     *
     * @param title
     */
    public void setTitle(String title) {
        mTitle.setText(title);
    }

    public boolean getOnItemLongClick(int position) {

        if (isMulChoice == false) {
            //如果现在不是长按状态,则进行长按操作
            List<EntryModel> data = adapter.getData();
            //把所有条目的对象都设置成等待选中状态
            for (EntryModel model : data) {
                model.setIsCheck(false);
                model.setIsLoading(false);
                model.setIsSingle(false);
                model.setIsLoading(true);
            }
            //把当前长按的这个条目设置为选中状态
            data.get(position).setIsCheck(true);
            updateAdapter();
            isMulChoice = true;
            //设置长按界面开启
            showLongLayout.setVisibility(View.VISIBLE);
            search_layouts.setVisibility(View.GONE);
            layout_num.setVisibility(View.VISIBLE);
            layout_title.setVisibility(View.GONE);
            return true;
        }
        return false;
    }

    /**
     * 执行点击事件
     *
     * @param position
     */
    public void getOnItemClick(int position) {
        EntryModel item = (EntryModel) adapter.getItem(position);
        if (isMulChoice == true) {
            //如果现在是长按状态,则点击的这个设置成选中状态
            item.setIsCheck(!item.isCheck());
            updateAdapter();
            return;
        }
        //点击文件夹
        String type = item.getMimeType();
        if (type.equals(FileConfig.TYPE_FOLDER)) {
            //如果是文件夹,则打开文件夹
            adapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{item.path + "/"}), getActivity(),listView);
            listView.setAdapter(adapter);
            setTitle(item.getFileName());
            currPath = item.path;
            currPosition = currPosition + "/" + position;
            paths += "/" + item.getFileName();
            search_result.setText(currPath);
        } else {
           openFile(item);
        }
    }

    /**
     * 更新适配器
     */
    protected void updateAdapter() {
        selectid.clear();
        adapter.notifyDataSetChanged();
        int selecedIndex = 0;
        for (EntryModel model : adapter.getData()) {
            if (model.isCheck()) {
                selecedIndex++;
                selectid.add(model);
//            }
            }
            selecedNumber.setText("已选中" + selecedIndex + "个");
            currSelseNum = selecedIndex;
            for (int i = 0; i < showLongLayout.getChildCount(); i++) {
                LinearLayout childAt = (LinearLayout) showLongLayout.getChildAt(i);
                ImageView img = (ImageView) childAt.getChildAt(0);
                TextView txt = (TextView) childAt.getChildAt(1);
                img.setImageResource(selecedIndex >= 1 ? img_white[i] : img_grey[i]);
                txt.setTextColor(selecedIndex >= 1 ? getResources().getColor(R.color.white) : getResources().getColor(R.color.grey));
            }
            if (selecedIndex > 1) {
                openFile_img.setImageDrawable(getResources().getDrawable(R.drawable.open_grey));
                openFile_txt.setTextColor(getResources().getColor(R.color.grey));
            }
        }
    }

    private void updateName() {
//        EntryModel fileModel = selectid/*.get(0);
//        Dao.getInstance(getActivity()).updateName(fileModel.getId(), fileModel.getMimeType(), newFileNmae.getText().toString());
//        for (EntryModel model : adapter.getData()) {
//            if (model.getId() == fileModel.getId()) {
//                model.setFileName(newFileNmae.getText().toString());
//            }
//        }
//        updateAdapter();
//        cancelLongClick();
//        alertDialog.dismiss();*/
    }

    /**
     * 重命名
     */
    private void reName() {
        //只有选中一个的时候，才可以重命名
        if (selectid.size() == 1) {
            openReName();
            window.dismiss();
        }
    }

    /**
     * 移动文件
     */
    private void moveFile() {
        Toast.makeText(getActivity(), "移动", Toast.LENGTH_SHORT).show();
    }

    /**
     * 选择所有或者取消所有
     */
    private void selecedAll() {
        for (EntryModel model : adapter.getData()) {
            initModel(model);
            if (isAllSeleced) {
                model.setIsCheck(false);
                model.setIsLoading(true);
            } else {
                model.setIsLoading(false);
                model.setIsCheck(true);
            }
        }
        isAllSeleced = !isAllSeleced;
        updateAdapter();
    }

    /**
     * 打开更多选项
     */
    private void openMoreFIle() {
        openMore();
    }

    /**
     * 下载文件
     */
    private void downLoad() {
        Toast.makeText(getActivity(), "下载" + selectid.size() + "个", Toast.LENGTH_SHORT).show();
    }

    /**
     * 删除文件
     */
    private void deleteFile() {
        final AlertDialog deleteDialog = getDialog("删除操作", "正在删除，请稍等!");
        if (currSelseNum >= 1) {
            deleteDialog.show();
            HttpUtils.getInstance().deleteFile(getActivity(), mApi, selectid, new OnDownLoadFinishListener() {
                @Override
                public void onSuccess(List<VDiskAPI.Entry> data) {
                    //如果没有选中东西,则直接退出
                    Dao.getInstance(getActivity()).deleteModel(selectid);
                    adapter.getData().removeAll(selectid);
                    updateAdapter();
                    cancelLongClick();
                    deleteDialog.dismiss();
                }

                @Override
                public void onFail(String errorInfo) {
                    Toast.makeText(getActivity(), "错误消息" + errorInfo, Toast.LENGTH_SHORT).show();
                }
            });

        }
    }

    public AlertDialog getDialog(String title, String message) {
        AlertDialog.Builder dialog = new AlertDialog.Builder(getActivity());
        AlertDialog alertDialog = dialog.create();
        alertDialog.setTitle(title);
        alertDialog.setMessage(message);
        alertDialog.setCancelable(false);
        return alertDialog;
    }

    /**
     * 打开文件
     */
    protected void openFile(EntryModel entryModel) {
        if (isMulChoice && currSelseNum == 1 || isMulChoice == false) {
            //你要打开文件，你如果是长按状态和你选中的只有一个,这样可以打开文件
            //如果选中的等于1,则可以进行打开
            if (entryModel != null) {
                if (entryModel.getMimeType().equals(FileConfig.TYPE_FOLDER)) {
                    //如果是文件夹，就打开文件夹
                    adapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{entryModel.path + "/"}), getActivity(),listView);
                    listView.setAdapter(adapter);
                    currPath = entryModel.path;
                    paths += "/" + entryModel.getFileName();
//                    tv_path.setText(currPath);
                    updateAdapter();
                    cancelLongClick();
                } else {
                    if (TextUtils.isEmpty(entryModel.getLocalpath())) {
                        //如果本地路径是空的，就是还没有下载，所以进行下载，下载完成后，进行打开
                        downloadFile(entryModel, entryModel.getPath(), new OnFileDownListener() {
                            @Override
                            public void onSuccess(EntryModel model) {
                                openFileByType(model.getLocalpath());
                            }

                            @Override
                            public void onFail(String errorInfo) {
                                Toast.makeText(getActivity(), "错误" + errorInfo, Toast.LENGTH_SHORT).show();
                            }
                        });
                    } else {
                        //如果有路径，则进行打开
                        openFileByType(entryModel.getLocalpath());
                    }
                    cancelLongClick();
                }
            }
        }

    }

    /**
     * 获取路径文件的后缀进行打开文件
     *
     * @param path
     */
    private void openFileByType(String path) {
        getActivity().startActivity(FileUtils.getInstance().openFile(path));
    }

    /**
     * 打开重命名窗口
     */
    private void openReName() {
        //初始化新建文件夹Dialog的控件
        View dialog_view = getActivity().getLayoutInflater().inflate(R.layout.item_dialog_rename, null);
        Button newFileNo = (Button) dialog_view.findViewById(R.id.dialog_cancel);
        newFileNmae = (EditText) dialog_view.findViewById(R.id.dialog_name);
        Button newFileYes = (Button) dialog_view.findViewById(R.id.dialog_yes);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        EntryModel fileModel = selectid.get(0);
        newFileNmae.setText(fileModel.getFileName());
        alertDialog = builder.create();
        alertDialog.setView(dialog_view);
        alertDialog.show();
        newFileYes.setOnClickListener(this);
        newFileNo.setOnClickListener(this);
    }

    /**
     * 打开更多
     */
    private void openMore() {
        window = new PopupWindow(getActivity().getResources().getDisplayMetrics().widthPixels / 3, ViewGroup.LayoutParams.WRAP_CONTENT);
        View view = getActivity().getLayoutInflater().inflate(R.layout.item_pop_more, null);
        view.findViewById(R.id.more_move).setOnClickListener(this);
        view.findViewById(R.id.more_rename).setOnClickListener(this);
        ImageView more_img = (ImageView) view.findViewById(R.id.more_img);
        TextView more_tv = (TextView) view.findViewById(R.id.more_tv_rename);
        window.setContentView(view);
        window.setOutsideTouchable(true);
        window.setFocusable(true);
        window.setBackgroundDrawable(new BitmapDrawable());
        int[] widthAndHeightforView = FileUtils.getWidthAndHeightforView(showLongLayout);
        window.showAtLocation(showLongLayout, Gravity.RIGHT | Gravity.BOTTOM, 0, widthAndHeightforView[1]);
        if (selectid.size() == 1) {
            //说明只有选中一个，可以重命名操作
            more_img.setImageResource(R.mipmap.edit_tools_rename);
            more_tv.setTextColor(getResources().getColor(R.color.white));
        } else {
            more_img.setImageResource(R.mipmap.edit_tools_rename_disable);
            more_tv.setTextColor(getResources().getColor(R.color.disable));
        }
    }

    public Activity getActivity() {
        return this;
    }

    private void initModel(EntryModel model) {
        model.setIsLoading(false);
        model.setIsCheck(false);
        model.setIsSingle(false);
    }

    /**
     * 退出长按事件
     */
    public void cancelLongClick() {
        List<EntryModel> data = adapter.getData();
        for (EntryModel model : data) {
            model.setIsSingle(true);
        }
        updateAdapter();
        isMulChoice = false;
        showLongLayout.setVisibility(View.GONE);
        layout_num.setVisibility(View.GONE);
        layout_title.setVisibility(View.VISIBLE);
        search_layouts.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == event.KEYCODE_BACK) {
            if (isMulChoice) {
                //如果在长按状态下按了返回，则退出长按状态
                cancelLongClick();
                return false;
            }
            if (!isSearch) {
                finish();
                return false;
            }
            if (currPath.equals("/")) {
                //如果已经是目录了，就不退了
                finish();
                return false;
            }
            //把当前路径分割，获取当前目录的上一个目录的ID
            if (currPath.contains("/")) {
                currPath = currPath.substring(0, currPath.lastIndexOf("/"));
            }
            String[] positons = currPosition.split("/");
            if (currPath.equals("")) {
                currPath = "/";
                adapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{"/"}), getActivity(),listView);
            } else {
                adapter = new FileAdapter(Dao.getInstance(getActivity()).getAllFile("parent_url=?", new String[]{currPath + "/"}), getActivity(),listView);
            }
            listView.setAdapter(adapter);
            try {
                listView.setSelection(Integer.valueOf(positons[positons.length - 1]));
            } catch (Exception ex) {
                Log.i("info", "转换异常216行");
            }
//          tv_path.setText(currPath.equals("/") ? "网盘" : currPath);
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void initCheck() {
        for (EntryModel item : adapter.getData()) {
            item.setIsCheck(false);
            item.setIsLoading(false);
            item.setIsSingle(true);
        }
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
        getOnItemClick(position);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long l) {
        return getOnItemLongClick(position);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.base_open:
                //打开文件
                if (selectid.size() == 1) {
                    //只有选中的等于1，才可以打开文件
                    openFile(selectid.get(0));
                }
                break;

            case R.id.base_delete:
                //删除文件
                if (selectid.size() > 0) {
                    //删除文件必须选中的文件大于0
                    deleteFile();
                }
                break;

            case R.id.base_down:
                //下载
                if (selectid.size() > 0) {
                    downNumb = selectid.size();
                    for (EntryModel model : selectid) {
                        File file = new File(OnlineConfig.DOWN_DIRECTORY+model.getFileName());
                        if(file.exists()){
                            Toast.makeText(getActivity(), "文件已下载，存储在下载目录中", Toast.LENGTH_SHORT).show();
                        }else{
                            Log.i("info", "执行插入");
                            FileTaskModel taskModel = new FileTaskModel();
                            taskModel.setFileName(model.getFileName());
                            taskModel.setPath(model.getPath());
                            taskModel.setProgress("0");
                            taskModel.setShal(model.getSha1());
                            taskModel.setType(model.getMimeType());
                            taskModel.setSize(model.getSize());
                            taskModel.setState(FileTaskModel.STATE_WAIT_DOWN);
                            taskModel.setTaskType(OnlineConfig.TYPE_DOWN);
                            Dao.getInstance(getActivity()).saveFileTask(taskModel);
                        }
                    }
                    //存储完成，执行提醒传输页面.
                    EventBus.getDefault().post(new String(OnlineConfig.TYPE_DOWN));
                    cancelLongClick();
                }else{
                    Toast.makeText(getActivity(), "不能下载"+selectid.size(), Toast.LENGTH_SHORT).show();
                }
                break;

            case R.id.base_more:
                //更多文件
                if (selectid.size() > 0) {
                    openMoreFIle();
                }
                break;

            case R.id.base_back:
                //返回键
                finish();
                break;

            case R.id.base_cancel:
                //取消多选
                cancelLongClick();
                break;

            case R.id.base_allseleced:
                //全选
                selecedAll();
                break;

            case R.id.more_move:
                //移动文件
                moveFile();
                break;

            case R.id.more_rename:
                //重命名
                reName();
                break;

            case R.id.dialog_yes:
                //点击确定修改名字
                updateName();
                break;

            case R.id.dialog_cancel:
                //点击取消修改名字
                alertDialog.dismiss();
                break;

        }
    }

    //下载文件
    private void downloadFile(String path) {

//        //TODO 下载文件
//        String targetPath = Environment.getExternalStorageDirectory()
//                .getAbsolutePath() + "/VDisk_SDK_cache/" + path;
//        DownloadFile downloadFile = new DownloadFile(null, BaseActivity.this,
//                mApi, path, targetPath, new OnFileDownListener() {
//            @Override
//            public void onSuccess(EntryModel model) {
//                currDownNum++;
//                if (currDownNum == downNumb) {
//                    Toast.makeText(getActivity(), "下载完成", Toast.LENGTH_SHORT).show();
//                    cancelLongClick();
//                }
//            }
//
//            @Override
//            public void onFail(String errorInfo) {
//                Toast.makeText(getActivity(), errorInfo, Toast.LENGTH_SHORT).show();
//            }
//        });
//        downloadFile.execute();
    }

    //下载文件
    private void downloadFile(EntryModel model, String path, OnFileDownListener onFileDownListener) {
        //TODO 下载文件
        String targetPath = Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/VDisk_SDK_cache/" + path;
//        DownloadFile downloadFile = new DownloadFile(model, getActivity(), mApi, path, targetPath, onFileDownListener);
//        downloadFile.execute();
    }

    //下载缩略图
    private void downloadThumbnail(final String path) {
        final Handler handler = new Handler();
        //  dialog.show();
        new Thread() {
            @Override
            public void run() {
                // Message msg = new Message();
                Bundle data = new Bundle();
                FileOutputStream mFos = null;
                try {
                    String cachePath = Environment
                            .getExternalStorageDirectory().getAbsolutePath()
                            + "/" + path + "";
                    try {
                        mFos = new FileOutputStream(cachePath, false);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                    mApi.getThumbnail(path, mFos, VDiskAPI.ThumbSize.ICON_640x480, null);
                    Log.i("info", "成功");
                } catch (VDiskException e) {
                    e.printStackTrace();
                    // msg.what = FAILED;
                }
                //  msg.setData(data);
                //  handler.sendMessage(msg);
            }
        }.start();
    }
}
